<template>
  <div class="delete-book-container">
    <h1>删除书籍</h1>
    <div class="search-box">
      <input
        v-model="searchTerm"
        type="text"
        placeholder="输入图书名称..."
        class="search-input"
        @keyup.enter="searchBooks"
      />
      <button @click="searchBooks" class="search-button">查询</button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="!loading && books.length > 0" class="book-results">
      <div v-for="book in books" :key="book.isbn" class="book-card">
        <h3>{{ book.title }}</h3>
        <p>作者：{{ book.author }}</p>
        <p>ISBN：{{ book.isbn }}</p>
        <p>剩余数量：{{ book.available_quantity }}</p>
        <p>状态：{{ book.status }}</p>
        <button @click="deleteBook(book)" class="delete-button">删除</button>
      </div>
    </div>

    <div v-if="!loading && books.length === 0 && searched" class="no-results">
      <p>未找到相关图书，请尝试其他关键词。</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "DeleteBook",
  data() {
    return {
      searchTerm: '',
      books: [],
      loading: false,
      searched: false,
      adminId: null, // 用于存储管理员ID
    };
  },
  created() {
    // 在组件创建时从本地存储中获取管理员ID
    this.loadAdminId();
  },
  methods: {
    // 从本地存储中加载管理员ID
    loadAdminId() {
      const user = JSON.parse(localStorage.getItem('user') || '{}');
      this.adminId = user.Id || null;
      if (!this.adminId) {
        console.error('管理员ID不存在');
        alert('管理员ID不存在，请重新登录');
      }
    },
    async searchBooks() {
      if (!this.searchTerm.trim()) {
        return;
      }

      this.loading = true;
      this.searched = true;

      try {
        const response = await axios.get(`http://8.134.212.44:9999/index/main/select?keyword=${this.searchTerm}`);
        // 提取后端返回的 data 字段
        this.books = response.data.data.map(book => ({
            title: book.Title,
            author: book.Author,
            isbn: book.Isbn,
            available_quantity: book.Available_quantity,
            status: book.Status
        }));
        console.log('提取后的书籍数据:', this.books); // 调试：打印提取后的数据
      } catch (error) {
        console.error('图书查询失败:', error);
        this.books = [];
      } finally {
        this.loading = false;
      }
    },
    async deleteBook(book) {
      if (!this.adminId) {
        alert('管理员ID获取失败，请重新登录');
        return;
      }

      try {
        const payload = {
          title: book.title,
          author: book.author,
          isbn: book.isbn,
          admin_id: this.adminId,
          // total_quantity:book.available_quantity,
        };

        await axios.post('http://8.134.212.44:9999/admin/delectbook', payload, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        alert('书籍删除成功');
        this.books = this.books.filter(b => b.isbn !== book.isbn);
      } catch (error) {
        console.error('删除书籍失败:', error);
        alert('删除书籍失败，请稍后重试。');
      }
    }
  }
};
</script>

<style scoped>
.delete-book-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
}

.search-box {
  display: flex;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px 0 0 4px;
}

.search-button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.loading {
  text-align: center;
  padding: 20px;
}

.book-results {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.book-card {
  width: calc(33.333% - 20px);
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.delete-button {
  margin-top: 10px;
  padding: 8px 15px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-button:hover {
  background-color: #c0392b;
}

.no-results {
  text-align: center;
  padding: 20px;
  color: #7f8c8d;
}
</style>